package com.xbh.notice.mq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.xbh.notice.model.NoticeMsg;
import com.xbh.notice.service.NoticeMsgServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

/**
 * @program: notice-center
 * @description:
 * @author: 许宝华
 * @create: 2021-12-16 09:47
 */
@Component
@Slf4j
public class SendMessage {


    @Autowired
    private NoticeMsgServiceImpl noticeMsgService;

    @RabbitListener(queues = "mc.send.message")
    @RabbitHandler
    @Transactional(rollbackFor = Exception.class)
    public void sendMessage(Message message, Channel channel) throws Exception {

        String msg = null;
        log.info(message.toString());
        try {
            msg=new String(message.getBody(),"UTF-8");

            NoticeMsg noticeMsg = JSON.parseObject(msg, NoticeMsg.class);

            log.info("消费者接收消息，保存成功");
            noticeMsgService.save(noticeMsg);

        } catch (Exception e) {

            log.error("通知消息保存异常",msg,e);

        } finally {
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (Exception e) {
                log.error("消息消费确认失败",e);
            }

        }
    }
}
